﻿/**订单排线begin**/
//Author:WANGYY
//创建任务ID
var taskid = "";
var setSigleBus = function (id, BuyClickCount, HallLossCount, task, order_Id) {
   // debugger
    if ((task == undefined || task == "") && top.document.cookie != "") {
        var array = top.document.cookie.match(new RegExp("taskid=([^\&]+)", "i"));
        if (array != null && array.length > 0)
            task = array[1];

    }
    //设置单一订单
    var $this = $(this);
    var sortstr = 1;
    // var sortstr = CPGridGlobal_GridObj.ColumnCol[15].val();
    var tmpUrlTmp = "/Plat/Grid/GridView?GridCode=Grid201809211659440061&PKValues=" + id + "&Sort=" + sortstr + "&ishall=1&BuyClickCount=" + BuyClickCount + "&HallLossCount=" + HallLossCount + "&taskid=" + task + "&order_id=" + order_Id;
    var OpenWinWidth = 1000;
    var OpenWinHeight = 700;
    tmpUrlTmp = FormatUrlForOpenNewModel(tmpUrlTmp, "top", "");
    top.OpenNewModel(tmpUrlTmp, "设置车辆", OpenWinWidth, OpenWinHeight);
};

function CPGridGetSortAndBuyCount() {
//debugger
    var sortstr = "";
    var buycountstr = 0;
    var hallcountstr = 0;
    var carnumer = "";
    var orderids = "";
    var order_id = "";
    $.each($(".CPGridChkCss"), function (nIndex, nObj) {        
        if ($(nObj).is(':checked')) {
            //debugger;
            //var id = $(nObj).val();
            $.each($("select[id^='CPGridEditControl_sortid_" + $(nObj).val() + "']"), function (sIndex, sObj) {
                sortstr += $(sObj).val() + "$";
            });
            sortstr = sortstr.substr(0, sortstr.length - 1);
            sortstr += ",";
            $.each($(nObj).parents('table').find('select[id^=CPGridEditControl_sortid_' + $(nObj).val() + ']'), function (index, obj) {
                //sortstr += parseInt($(obj).val()) + ",";
                var trobj = $(obj).parents('tr');
               // var halllossObj = $(obj).parents('td').prev();
               // var buyObj = halllossObj.prev();
                var halllossObj = $("#CPGridControl_HallLossCount_" + $(nObj).val() + "");
                var buyObj = $("#CPGridControl_BuyChickCount_" + $(nObj).val() + "");
                buycountstr += parseInt(buyObj[0].innerText);
                hallcountstr += parseInt(halllossObj[0].innerText);
                if (trobj.find("span[id^='CPGridControl_carNumber_']").length === 0 && carnumer == "")
                    carnumer = trobj.find("span[id^='CPGridControl_carNumber_']").text();
            });
            orderids += ($(nObj).parents('td').next()[0]).innerText + ",";
            order_id += $(nObj).val() + ",";
        }
    });
    orderids = orderids.substr(0, orderids.length - 1);
    order_id = order_id.substr(0, order_id.length - 1);
    return sortstr.substr(0, sortstr.length - 1) + "&" + buycountstr + "&" + hallcountstr + "&" + carnumer + "&" + orderids + "&" + order_id;
}

var setMultipleBus = function () {//设置多个订单
    debugger
    var str = CPGridGetSortAndBuyCount();
    var strsplit = str.split("&");
    var sortstr = strsplit[0];
    var buycountstr = strsplit[1];
    var hallcountstr = strsplit[2];
    var carnumber = strsplit[3];
    var orderids = strsplit[4];
    var order_id = strsplit[5];
    var task = getQueryString("taskid");

    if (top.document.cookie != "" && task == undefined) {
        var array = top.document.cookie.match(new RegExp("taskid=([^\&]+)", "i"));
        if (array != null && array.length > 0)
            task= array[1];

    }
    if (sortstr.length <= 0) {
        alert("请选择要设置车辆的订单！");
        return false;
    }
    var id = CPGridGetInfo();

    // var sortstr = CPGridGlobal_GridObj.ColumnCol[15].val();
    var tmpUrlTmp = "/Plat/Grid/GridView?GridCode=Grid201809291426280072&PKValues=" + id + "&Sort=" + sortstr + "&ishall=0&BuyClickCount=" + buycountstr + "&HallLossCount=" + hallcountstr + "&taskid=" + task + "&carnumber=" + carnumber + "&orderids=" + orderids + "&order_id=" + order_id;
    var OpenWinWidth = 1000;
    var OpenWinHeight = 700;
    tmpUrlTmp = FormatUrlForOpenNewModel(tmpUrlTmp, "top", "");
    top.OpenNewModel(tmpUrlTmp, "设置车辆", OpenWinWidth, OpenWinHeight);
};

//批量设置车辆//
var bindBusAndForm = function () {debugger
    //订单设置车辆
    var inputObj = new Object();
    var ishall = getQueryString("ishall");
    if (ishall === '0')
        inputObj.OrderIds = getQueryString("PKValues");
    else
        inputObj.HallIds = getQueryString("PKValues");
    if (inputObj.OrderIds === null) inputObj.OrderIds = "";
    if (inputObj.HallIds === null) inputObj.HallIds = "";
    inputObj.Sorts = getQueryString("Sort");
    if (inputObj.Sorts === null) inputObj.Sorts = "";
    inputObj.CarIds = CPGridGetCarInfo();
    if (taskid === "") inputObj.TaskID = getQueryString("taskid");
    else inputObj.TaskID = taskid;
    if (inputObj.TaskID === "undefined") inputObj.TaskID = "";
    
    if (inputObj.CarIds.length <= 0) {
        alert("请选择车辆信息！");
        return false;
    }
    if (!verify(inputObj.CarIds)) { alert("进雏数量与运输数量，或路耗与运输路耗不符，请重新设置"); return false; }
    inputObj.GridCode = CPGridGlobal_GridObj.GridCode;
    inputObj.CurUserId = CPCurUserId;
    inputObj.CurUserIden = CPCurUserIden;
    var url = "/api/OrderFormCable/SetTaskCar";

    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(inputObj),
        contentType: 'application/json',
        success: function (data) {
            if (data.Result === false) {
                alert("设置失败，详细信息：" + data.ErrorMsg);
                return false;
            }
            else {
               // debugger
                //window.taskid = data.ErrorMsg; 
                top.document.cookie = "taskid=" + data.ErrorMsg;
                alert("设置成功！");
                //top.CPRefresh();
               // parent.location.reload(); 
                // window.top.frames[2].document
                //if (parent.CPRefresh !== undefined) parent.CPRefresh();
                bindCarNumber();
                if (top.CPRefresh !== undefined) top.CPRefresh();
                if (top.CPGridRefresh !== undefined) top.CPGridRefresh();
                top.CloseNewModel();
            }
        }
    });
};

//验证孵化厅数量与车辆的运输数量
var verify = function (Items) {
    $("input[id^='CPGridEditControl_BuyClickCount_']").removeAttr("style");
    $("input[id^='CPGridEditControl_HallLossCount_']").removeAttr("style");
    if (Items === undefined) return false;
    var BuyChickCount = 0, HallLossCount = 0;
    var BuyClickCounttotal = getQueryString('BuyClickCount');
    var HallLossCounttotal = getQueryString('HallLossCount');
    var flag = true;
    $.each(Items, function (nIndex, nObj) {
        var tmp = new Object();
        HallLossCount += parseInt(nObj.HallLossCount);
        BuyChickCount += parseInt(nObj.BuyClickCount);

        if ((HallLossCount != parseInt(HallLossCounttotal) || BuyChickCount != parseInt(BuyClickCounttotal))
            && BuyChickCount != 0 && nIndex + 1 == Items.length) {
            flag = false;
        }
    });
    if (flag == false) {
        $.each($(".CPGridChkCss"), function (nIndex, nObj) {
            if ($(nObj).is(':checked')) {
                $("input[id^='CPGridEditControl_BuyClickCount_" + $(nObj).val() + "']").css('background-color', '#d81e06');
                $("input[id^='CPGridEditControl_HallLossCount_" + $(nObj).val() + "']").css('background-color', '#d81e06');
            }
        });
        return false;
    } else return true;

};



var bindCarNumber = function () {
    debugger;
    var order_id = getQueryString("order_id");
    var PKValues = getQueryString("PKValues");
    var ishall = getQueryString("ishall");
    if (order_id != undefined && order_id != "") {
        var strsplit = order_id.split(',');
        var carnumber = "";
        var names = "";
        var carinfo = CPGridGetCarInfo(); 
        $.each(carinfo, function (cIndex, cObj) {
            // debugger;
            carnumber += cObj.CarNumber + ",";
            names += cObj.CarNumber + "[" + cObj.MainDriverName + "," + cObj.AssistantDriverName + "],";
        });

        carnumber = carnumber.substr(0, carnumber.length - 1);
        $.each(strsplit, function (nIndex, nObj) {
           // debugger;
            //$("#CPGridControl_carNumber_" + nObj, window.top.frames[2].document).text(carnumber);
            if ($("span[id^='CPGridControl_carNumber_" + nObj + "']", window.top.frames[2].document).length == 0) {
                if (ishall == 1)
                    $("input[id^='CPGridEditControl_code_" + PKValues + "']", window.top.frames[2].document).parents('tr').find("#CPGridControl_setCar_" + nObj).text(carnumber);
                else
                    // $("a[id^='CPGridControl__" + nObj + "']", window.top.frames[2].document).text(carnumber);
                    $.each($("a[id^='CPGridControl_setCar_" + nObj + "']", window.top.frames[2].document), function (fIndex, fObj) {
                        $(fObj).text(carnumber);
                    });
            }
            else {
                if (ishall == 1)
                    $("input[id^='CPGridEditControl_code_" + PKValues + "']", window.top.frames[2].document).parents('tr').find("#CPGridControl_carNumber_" + nObj).text(carnumber);
                else
                    $.each($("span[id^='CPGridControl_carNumber_" + nObj + "']", window.top.frames[2].document), function (bIndex, bObj) {
                        $(bObj).text(carnumber);
                    });
            }
            //$("#CPGridControl_carNumber_" + nObj, window.top.frames[2].document).text(carnumber);
            //$("span[id^='#CPGridControl_carNumber_" + nObj + "']", window.top.frames[2].document).text(carnumber);
        });
    }
};

var updateBindBusAndForm = function () {

   // debugger


    //订单设置车辆
    var inputObj = new Object();
    inputObj.OrderIds = "";
    inputObj.HallIds = "";
    inputObj.Sorts = getQueryString("Sort");
    if (inputObj.Sorts === null) inputObj.Sorts = "";
    inputObj.CarIds = CPGridGetCarInfo();    
    if (taskid === "") inputObj.TaskID = getQueryString("taskid");
    else inputObj.TaskID = taskid;
    if (inputObj.TaskID === "undefined") inputObj.TaskID = "";
    inputObj.BuyClickCount = "";
    if (inputObj.CarIds.length <= 0) {
        alert("请选择车辆信息！");
        return false;
    }
    inputObj.GridCode = CPGridGlobal_GridObj.GridCode;
    inputObj.CurUserId = CPCurUserId;
    inputObj.CurUserIden = CPCurUserIden;


    var url = "/api/OrderFormCable/SetUpdateTaskCar";

    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(inputObj),
        contentType: 'application/json',
        success: function (data) {
            if (data.Result === false) {
                alert("设置失败，详细信息：" + data.ErrorMsg);
                return false;
            }
            else {
               // debugger
                top.document.cookie = "taskid=" + data.ErrorMsg;
                taskid = data.ErrorMsg;
                alert("设置成功！");
                if (top.CPRefresh !== undefined) top.CPRefresh();
                if (top.CPGridRefresh !== undefined) top.CPGridRefresh();
                top.CloseNewModel();
            }
        }
    });
};

//新增任务下的订单
var saveOrderForTask = function () {
    //debugger
    var inputObj = new Object();
    var id = CPGridGetInfo();
    var str = CPGridGetSortAndBuyCount();
    var strsplit = str.split("&");
    var sortstr = strsplit[0];
    var task = getQueryString("taskid");
    if (task == undefined && top.document.cookie != "") {
        var array = top.document.cookie.match(new RegExp("taskid=([^\&]+)", "i"));
        if (array != null && array.length > 0)
            task = array[1];

    }
    if (id.length <= 0) {
        alert("请选择要保存的订单！");
        return false;
    }
    inputObj.GridCode = CPGridGlobal_GridObj.GridCode;
    inputObj.CurUserId = CPCurUserId;
    inputObj.CurUserIden = CPCurUserIden;
    inputObj.OrderIds = id;
    inputObj.TaskID = task;
    inputObj.Sorts = sortstr;
    var url = "/api/OrderFormCable/saveOrderForTask";
    


    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(inputObj),
        contentType: 'application/json',
        success: function (data) {
            if (data.Result === false) {
                alert("保存失败，详细信息：" + data.ErrorMsg);
                return false;
            }
            else {
                taskid = data.ErrorMsg;
                alert("保存成功！");
                if (top.CPRefresh !== undefined) top.CPRefresh();
                if (top.CPGridRefresh !== undefined) top.CPGridRefresh();
            }
        }
    });
};

function CPGridGetCarInfo() {
    debugger
    var Items = new Array();
    //多选框
    if (CPGridGlobal_GridObj.ColumnCol[0].ColumnType === 2) {
        $.each($(".CPGridChkCss"), function (nIndex, nObj) {
            if ($(nObj).is(':checked')) {
                var tmp = new Object();
                tmp.DataPK = $(nObj).val();
                tmp.AssistantDriverId = "";
                tmp.MainDriverID = "";
                tmp.BuyClickCount = 0;
                tmp.CarNumber = "";
                $.each(CPGridGlobal_GridObj.ColumnCol, function (cIndex, cObj) {
                    tmp.MainDriverID = $("#CPGridEditControl_MainDriverId_" + tmp.DataPK).val(); 
                    tmp.AssistantDriverId = $("#CPGridEditControl_AssistantDriverId_" + tmp.DataPK).val();
                    tmp.BuyClickCount = $("#CPGridEditControl_BuyClickCount_" + tmp.DataPK).val();
                    tmp.HallLossCount = $("#CPGridEditControl_HallLossCount_" + tmp.DataPK).val();
                    tmp.CarNumber = $("#CPGridControl_CarNumber_" + tmp.DataPK).text();
                    tmp.MainDriverName = $("#CPGridEditControl_MainDriverId_" + tmp.DataPK).find("option:selected").text();
                    tmp.AssistantDriverName = $("#CPGridEditControl_AssistantDriverId_" + tmp.DataPK).find("option:selected").text();
                    return false;
                });
                Items.push(tmp);
            }
        });
    }
    //单选框
    if (CPGridGlobal_GridObj.ColumnCol[0].ColumnType === 3) {
        $.each($(".CPGridRadioCss"), function (nIndex, nObj) {
            if ($(nObj).is(':checked')) {
                var tmp = new Object();
                tmp.DataPK = $(nObj).val();
                $.each(CPGridGlobal_GridObj.ColumnCol, function (cIndex, cObj) {
                    tmp.MainDriverID = $("#CPGridEditControl_MainDriverId_" + tmp.DataPK).val();
                    if (tmp.MainDriverID === "") tmp.MainDriverID = 0;
                    tmp.AssistantDriverId = $("#CPGridEditControl_AssistantDriverId_" + tmp.DataPK).val();
                    if (tmp.AssistantDriverId === "") tmp.AssistantDriverId = 0;
                    tmp.BuyClickCount = $("#CPGridEditControl_BuyClickCount_" + tmp.DataPK).val();
                    if (tmp.BuyClickCount === "") tmp.BuyClickCount = 0;
                    tmp.HallLossCount = $("#CPGridEditControl_HallLossCount_" + tmp.DataPK).val();
                    if (tmp.HallLossCount === "") tmp.HallLossCount = 0;
                    tmp.CarNumber = $("#CPGridControl_CarNumber_" + tmp.DataPK).text();
                    tmp.MainDriverName = $("#CPGridEditControl_MainDriverId_" + tmp.DataPK).find("option:selected").text();
                    tmp.AssistantDriverName = $("#CPGridEditControl_AssistantDriverId_" + tmp.DataPK).find("option:selected").text();
                    return false;
                });
                Items.push(tmp);
            }
        });
    }
    return Items;
}

//删除任务下的订单信息及配置车辆信息
var DelTaskInfo = function () {
    var inputObj = new Object();
    var id = CPGridGetInfo();
    var task = getQueryString("taskid");
    if (id.length <= 0) {
        alert("请选择要删除的订单！");
        return false;
    }
    inputObj.GridCode = CPGridGlobal_GridObj.GridCode;
    inputObj.CurUserId = CPCurUserId;
    inputObj.CurUserIden = CPCurUserIden;
    inputObj.Order_Id = id;
    inputObj.TaskID = task;



    var url = "/api/OrderFormCable/DelOrderANDCarForTask";



    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(inputObj),
        contentType: 'application/json',
        success: function (data) {
            if (data.Result === false) {
                alert("删除失败，详细信息：" + data.ErrorMsg);
                return false;
            }
            else {
                taskid = data.ErrorMsg;
                alert("删除成功！");
                CPGridRefresh();
            }
        }
    });
};

function CPGridGetInfo() {
    var str = "";
    $.each($(".CPGridChkCss"), function (nIndex, nObj) {
        if ($(nObj).is(':checked')) {            
            str += parseInt($(nObj).val()) + ",";
        }
    });
    return str.substr(0, str.length - 1);
}
//获取url中的参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); // 匹配目标参数
    var result = window.location.search.substr(1).match(reg);  // 对querystring匹配目标参数
    if (result !== null) {
        return decodeURIComponent(result[2]);
    } else {
        return null;
    }
}

$(document).ready(function () {
    //默认绑定
   // debugger

    if (CPGridGlobal_GridObj.ColumnCol[0].ColumnType === 2 || CPGridGlobal_GridObj.ColumnCol[0].ColumnType === 3) {
        var FieldEnumDataIns = CPGridGlobal_GridObj.ColumnCol[0].FieldEnumDataIns;
        var FieldEnumDataSource = CPGridGlobal_GridObj.ColumnCol[0].FieldEnumDataSource;
        if (FieldEnumDataSource !== "" && FieldEnumDataSource !== null) {
            var GridCode = CPGridGlobal_GridObj.GridCode;
            var CurUserId = CPCurUserId;
            var CurUserIden = CPCurUserIden;

            var url = "/api/OrderFormCable/GetPrimarykeySource?GridCode=" + GridCode + "&CurUserId=" + CurUserId + "&CurUserIden=" + CurUserIden;
            //为了表达式，需要把URL里其它字段再加上
            //再加其它参数
            var sResultArray = CPGetQueryString();
            for (var mm = 0; mm < sResultArray.length; mm++) {
                var tempSarray = sResultArray[mm].split('=');
                if (tempSarray[0].toLowerCase() === "gridcode"
                    || tempSarray[0].toLowerCase() === "curuserid"
                    || tempSarray[0].toLowerCase() === "curuseriden"
                    || tempSarray[0].toLowerCase() === "othercondition"
                )
                    continue;
                url += "&" + sResultArray[mm];
            }
            $.getJSON(url, function (data) {
                //debugger
                if (data === "null" || data.length === 0) return;
                //绑定
                data = eval('(' + data[0] + ')');
                bindCPGridChk(data);

            });
        }
    }
    //绑定多选框
    var bindCPGridChk = function (data) {
       // debugger
        $.each(data, function (dIndex, dObj) {
            if (CPGridGlobal_GridObj.ColumnCol[0].ColumnType === 2) {

                $.each($(".CPGridChkCss"), function (nIndex, nObj) {
                    if ($(nObj).val() === dObj.id)
                        $(nObj).attr("checked", "checked");
                });
            }
            if (CPGridGlobal_GridObj.ColumnCol[0].ColumnType === 3) {
                $.each($(".CPGridRadioCss"), function (nIndex, nObj) {
                    if ($(nObj).val() === dObj.id)
                        $(nObj).attr("checked", "checked");
                });
            }
        });

    };

    //绑定初始时间
    //debugger;
    if ($("#CPGridQueryControl_WaitDeliveryTime").val() === "" && getQueryString("WaitDeliveryTime") !== null && getQueryString("WaitDeliveryTime") != undefined) {
        var WaitDeliveryTime = getQueryString("WaitDeliveryTime");
        $("#CPGridQueryControl_WaitDeliveryTime").val(WaitDeliveryTime);
        CPGridSearch();
    }

   
    //绑定序列字段
    $.each($("input[id^='CPGridControl_sort_']"), function (nIndex, nObj) {debugger
        if ($(nObj).val() !== "1") {
            var cObj = $(nObj).parents('td').find('select');            
            $(cObj).find("option[value='" + $(nObj).val() + "']").attr("selected", true);          
        }
    });

});
/**end**/


/**排线修改begin**/
//审核
function check(id, taskid, carNumber) {
    //debugger
    var updateObj = new Object();
    updateObj.GridCode = CPGridGlobal_GridObj.GridCode;
    updateObj.CurUserId = CPCurUserId;
    updateObj.CurUserIden = CPCurUserIden;
    updateObj.taskid = taskid;
    updateObj.DeliveryTaskStatus = 0;
    updateObj.carNumber = carNumber;
    updateObj.CarDeliveryTaskStatus = 0;
    var url = CPWebRootPath + "/api/OrderFormCable/AdjustDeliveryTaskStatus";


    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(updateObj),
        contentType: 'application/json',
        success: function (data) {
            if (data.Result == false) {
                alert("未通过，详细信息：" + data.ErrorMsg);
                return false;
            } else {
                alert("已通过！");
                CPGridRefresh();
            }
        }
    });


}

function GetDatUpdate(id, val) {
    var Items = new Array();
    var tmp = new Object();
    tmp.DataPK = id;
    tmp.FieldNamCol = new Array();
    tmp.FieldValueCol = new Array();
    tmp.FieldNamCol.push("CarDeliveryTaskStatus");
    tmp.FieldValueCol.push(parseInt(val));
    Items.push(tmp);
    return Items;

}
//撤销
function revoke(id, taskid, carNumber) {
    var url = CPWebRootPath + "/api/OrderFormCable/AdjustDeliveryTaskStatus";
    var updateObj = new Object();
    updateObj.GridCode = CPGridGlobal_GridObj.GridCode;
    updateObj.CurUserId = CPCurUserId;
    updateObj.CurUserIden = CPCurUserIden;
    updateObj.taskid = taskid;
    updateObj.DeliveryTaskStatus = -1;
    updateObj.carNumber = carNumber;
    updateObj.CarDeliveryTaskStatus = -1;

    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(updateObj),
        contentType: 'application/json',
        success: function (data) {
            if (data.Result == false) {
                alert("撤销失败，详细信息：" + data.ErrorMsg);
                return false;
            } else {
                alert("撤销完成！");
                CPGridRefresh();
            }
        }
    });

}
/**end**/